<template>
  <div class="params">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home/welcome">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容区域 -->
    <el-card>
      <div slot="header">
        <!-- 提示信息区域 -->
        <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
        <!-- 选择商品分类区域 -->
      </div>
      <!-- 级联选择器函数 -->
      <el-row>
        <el-col>
          选择商品分类：
          <!-- 两层分类数据的展示 -->
          <el-cascader
            size="medium"
            v-model="selectCate"
            :options="parentCateList"
            :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children'}"
            @change="parentChange"
            clearable
            filterable
            ref="parentCateList"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- nav区域 -->
      <el-row class="navList">
        <el-col>
          <el-tabs v-model="navSelect" @tab-click="parentChange">
            <!-- 动态参数的面板 -->
            <el-tab-pane label="动态参数" name="many">
              <el-button type="primary" size="mini" @click="addflag = true" :disabled="isSel">添加参数</el-button>
              <!-- 展示属性区域 -->
              <el-table :data="manyContent" border style="width: 100%" stripe>
                <!-- 第一个为展开行 -->
                <el-table-column type="expand" width="100">
                  <template slot-scope="scope">
                    <el-col :span="20">
                      <el-tag
                        v-for="(item,index) in scope.row.attr_vals"
                        :key="index"
                        closable
                        @close="deleteTag(index,scope.row)"
                      >{{item}}</el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @blur="handleInputConfirm(scope.row)"
                      ></el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showInput(scope.row)"
                      >+ New Tag</el-button>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="#" width="180"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称" width="180"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="small"
                      @click="addHot(scope.row)"
                    >编辑</el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete-solid"
                      size="small"
                      @click="deleteAttr(scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 静态属性的面板 -->
            <el-tab-pane label="静态属性" name="only">
              <el-button type="primary" size="mini" @click="addflag = true" :disabled="isSel">添加属性</el-button>
              <!-- 展示属性区域 -->
              <el-table :data="manyContent" border style="width: 100%" stripe>
                <!-- 第一个为展开行 -->
                <el-table-column type="expand" width="100">
                  <template slot-scope="scope">
                    <el-col :span="20">
                      <el-tag
                        v-for="(item,index) in scope.row.attr_vals"
                        :key="index"
                        closable
                        @close="deleteTag(index,scope.row)"
                      >{{item}}</el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @blur="handleInputConfirm(scope.row)"
                      ></el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showInput(scope.row)"
                      >+ New Tag</el-button>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="#" width="180"></el-table-column>
                <el-table-column prop="attr_name" label="属性名称" width="180"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="small"
                      @click="addHot(scope.row)"
                    >编辑</el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete-solid"
                      size="small"
                      @click="deleteAttr(scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <!-- 添加参数或者属性的对话框 -->
      <el-dialog :title="titleText" :visible.sync="addflag" width="50%" @close="resetForm">
        <el-form
          :model="addParamForm"
          :rules="paramRules"
          ref="addParamForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParamForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addflag = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- card body -->
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 接收分类的信息
      parentCateList: [],
      // 级联器中选择的信息
      selectCate: [],
      // nav中选择的内容
      navSelect: 'many',
      // 动态参数与静态属性数据存储的内容
      manyContent: [],
      // 添加的对话框标志
      addflag: false,
      // 添加的表单信息
      addParamForm: {
        attr_name: ""
      },
      // 添加的信息验证
      paramRules: {
        attr_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ]
      },
      // 当前编辑的对象
      curobj: null,
      // 标签中输入框是否显示
      inputVisible: false,
      // 标签输入框中存储的内容
      inputValue: ''
    }
  },
  created () {
    // 获取分类列表
    this.getParentCateList();
  },
  computed: {
    // 对按钮的限制  没有选中级联器的三级之前不允许点按钮
    isSel () {
      if (this.selectCate.length == 3)
        return false
      else
        return true;
    },
    // 返回选择的分类id
    cId () {
      if (this.selectCate.length == 3)
        return this.selectCate[2]
      else
        return null;
    },
    // 判断显示哪个标题
    titleText () {
      if (this.navSelect == 'many')
        return '动态参数'
      else
        return '静态属性'
    }
  },

  methods: {
    async getParentCateList () {
      // 因为分类只需要获取前两层 所以为2
      let res = await this.axios.get("categories", { params: { type: 3 } });
      if (res.meta.status != 200)
        return this.$message.error(
          {
            message: "获取全部分类数据失败",
            duration: 1000
          }
        )
      this.parentCateList = res.data;
    },
    // 当分类选择出现变化时 触发
    parentChange () {
      console.log(this.selectCate);
      if (this.selectCate.length != 3) {
        this.selectCate = [];
        this.manyContent = [];
        return;
      }
      // 选择三级分类后   去取相应分类的数据
      this.axios.get("categories/" + this.cId + "/attributes", { params: { sel: this.navSelect } })
        .then(res => {
          if (res.meta.status != 200) return;
          // 对展示的tag字符串作分割
          res.data.forEach(item => {
            if (!item.attr_vals) item.attr_vals = [];
            else
              item.attr_vals = item.attr_vals.split(" ");
            item.inputVisible = false;
            item.inputValue = "";
          });
          this.manyContent = res.data;
          console.log(this.manyContent);
        })
    },
    // 添加参数
    addParams () {
      if (!this.curobj)
        this.$refs.addParamForm.validate(async valid => {
          if (!valid) return;
          let res = await this.axios.post("categories/" + this.cId + "/attributes", { attr_name: this.addParamForm.attr_name, attr_sel: this.navSelect });
          if (res.meta.status != 201)
            return this.$message.error({
              message: "添加参数失败",
              duration: 1000
            });
          this.$message.success({
            message: "添加参数成功",
            duration: 1000
          })

          await this.parentChange();
          this.addflag = false;
        })
      else
        this.saveHot(this.curobj);
    },
    // 重置表单
    resetForm () {
      console.log(this.$refs.addParamForm);
      this.curobj = null;
      this.addParamForm.attr_name = ""
      // 清空数组的同时清空 选择的数据
    },
    // 添加属性和参数按钮触发的事件
    addHot (row) {
      this.addflag = true;
      this.curobj = row;
      this.addParamForm.attr_name = row.attr_name;
      console.log(this.curobj);
    },
    // 编辑参数
    saveHot (row) {
      this.$refs.addParamForm.validate(async valid => {
        if (!valid) return;
        let res = await this.axios.put("categories/" + this.cId + "/attributes/" + row.attr_id, { attr_name: this.addParamForm.attr_name, attr_sel: this.navSelect, attr_vals: row.inputValue ? row.inputValue : "" });
        if (res.meta.status != 200)
          return this.$message.error({
            message: "编辑" + this.titleText + "失败",
            duration: 1000
          });
        this.$message.success({
          message: "编辑" + this.titleText + "成功",
          duration: 1000
        })

        await this.parentChange();
        this.addflag = false;
        this.curobj = null;
      })
    },
    //  删除参数或属性
    deleteAttr (row) {
      this.$confirm("此操作将永久删除该" + this.titleText + ", 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 发送请求去删除数据
          this.axios.delete("categories/" + this.cId + "/attributes/" + row.attr_id).then(res => {
            if (res.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              // 重新获取数据
              this.parentChange();
            } else {
              this.$message.error({
                message: "删除失败",
                duration: 1000
              });
            }
          });
        })
        .catch(() => { });
    },
    // 显示标签中的输入框
    showInput (row) {
      row.inputVisible = true;
      // 在下一次更新后聚焦
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 移除焦点添加标签中内容到数据库
    async  handleInputConfirm (row) {
      row.inputVisible = false;
      if (!row.inputValue) return;
      row.attr_vals.push(row.inputValue);
      let res = await this.axios.put("categories/" + this.cId + "/attributes/" + row.attr_id, { attr_name: row.attr_name, attr_sel: this.navSelect, attr_vals: row.attr_vals.join(" ") });
      console.log(res);

      if (res.meta.status != 200)
        return this.$message.error({
          message: "添加失败",
          duration: 1000
        });
      this.$message.success({
        message: "添加成功",
        duration: 1000
      })
      row.inputValue = '';
    },
    // 删除标签
    async deleteTag (index, row) {
      this.$confirm("此操作将永久删除该标签, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          // 发送请求去删除数据
          row.attr_vals = row.attr_vals.filter((item, i) => {
            return i != index;
          })
          let res = await this.axios.put("categories/" + this.cId + "/attributes/" + row.attr_id, { attr_name: row.attr_name, attr_sel: this.navSelect, attr_vals: row.attr_vals.join(" ") });
          console.log(res);
          if (res.meta.status != 200)
            return this.$message.error({
              message: "删除失败",
              duration: 1000
            });
          this.$message.success({
            message: "删除成功",
            duration: 1000
          })
        })
        .catch(() => { });
    }
  },
}
</script>

<style lang="scss">
.params {
  .el-card__body {
    text-align: left;
  }
  .navList {
    margin-top: 10px;
  }
  .el-dialog {
    text-align: center;
  }
  .el-tag {
    margin: 10px;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
  }
}
</style>